package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.blood_pressure

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_bloodpressure.BloodPressure
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.BpBloodPressureNewRecordActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_history.BpBloodPressureHistoryListActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_report.BloodPressureResultActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_view.BloodPressureViewActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.tracker.BpTrackerAdapterClickListener
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.tracker.BpTrackerBloodPressureAdapter
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.bp_view.BPTrackSpacingItemDecoration
import com.bp.hearthealth.pulse.lnapps.databinding.BloodPressureFragmentBgBinding
import org.koin.androidx.viewmodel.ext.android.viewModel


class BloodPressureFragment : BpBaseFragment<BloodPressureFragmentBgBinding>(),
    BpTrackerAdapterClickListener {

    private val viewModel: BloodPressureViewModel by viewModel()
    private val trackerBloodPressureAdapter = BpTrackerBloodPressureAdapter()
    private var type = ""

    companion object {
        fun newInstance(type: String): BloodPressureFragment {
            val fragment = BloodPressureFragment()
            val args = Bundle()
            args.putString(Constants.BLOOD_PRESSURE_FRAGMENT, type)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        type = arguments?.getString(Constants.BLOOD_PRESSURE_FRAGMENT).toString()
        LogUtil.i("BloodPressureFragment：type $type")
    }

    override fun loadDataOnce() {
        super.loadDataOnce()
        registerObserver()
        initRecyclerView()
        loadViewAllData()
        if (type == Constants.BLOOD_PRESSURE_ACTIVITY) {
            //只在Done跳转过来的进行埋点及Activity跳转
            AppsFlyerUtils.trackEvent("bp_show")
            setLlAddView()
        }
    }

    private fun setLlAddView() {
        val layoutParams = binding.llAdd.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
        layoutParams.bottomMargin = 0
        binding.llAdd.layoutParams = layoutParams
    }

    private fun loadViewAllData() {
        //查询指定时间范围内的数据
        viewModel.getBloodPressureDataForDateRange(Constants.USER_ID)
        //查询最近3条数据
        viewModel.getLast3BloodPressureData(Constants.USER_ID)
        //查询筛选数据
        viewModel.getFilterData(Constants.USER_ID)
        //获取Statistics全部数据
        viewModel.getStatisticsStateType(Constants.USER_ID)
        //获取BloodPressure对象所有数据
//        viewModel.getAllBloodPressure(Constants.USER_ID)
    }

    private fun registerObserver() {
        BpLiveDataBus.with<Boolean>(Constants.REFRESH_TRACKER).observe(this) {
            loadViewAllData()
        }
        //指定时间范围内的数据
        viewModel.queueBloodPressureData.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response.isNullOrEmpty()) {
                trackerBloodPressureAdapter.setViewListData(emptyList())
                return@Observer
            }
            LogUtil.i("时间段数据位：$response")
            setViewSortData(response)
        })
        //5中类型筛选
        viewModel.filfter.observe(this, Observer { map ->
            if (map.isNullOrEmpty()) {
                trackerBloodPressureAdapter.setFilterMapValue(emptyMap())
                return@Observer
            }
            trackerBloodPressureAdapter.setFilterMapValue(map)
        })
        //Statistics数据
        viewModel.statusTypes.observe(this, Observer { result ->
            if (result.isNullOrEmpty()) {
                trackerBloodPressureAdapter.setStatisticsCount(emptyList())
                viewModel.listSize.set(0)
                return@Observer
            }
            viewModel.listSize.set(result.size)
            trackerBloodPressureAdapter.setStatisticsCount(result)
        })
        //最近3条数据
        viewModel.lastThreeData.observe(this, Observer { result ->
            val list = result.getOrNull()
            binding.recyclerView.itemAnimator?.changeDuration = 0
            if (list.isNullOrEmpty()) {
                trackerBloodPressureAdapter.setDataThreeList(emptyList())
                return@Observer
            }
            LogUtil.i("最近3条列表数据：$list")
            trackerBloodPressureAdapter.setDataThreeList(list)

        })
        //查询所有数据
        viewModel.bloodPressureList.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response.isNullOrEmpty()) {
                trackerBloodPressureAdapter.setViewListData(emptyList())
                return@Observer
            }
            setViewSortData(response)
        })
    }

    private fun setViewSortData(response: List<BloodPressure>) {
        // 对列表按照 timePeriod 升序排序
        val sortedResponse = response.sortedBy { bloodPressure ->
            bloodPressure.bloodPressureList.minByOrNull { it.timePeriod }?.timePeriod
                ?: Long.MAX_VALUE
        }
        viewModel.listSize.set(sortedResponse.size)
        LogUtil.i("数据列表为：$sortedResponse")
        trackerBloodPressureAdapter.setViewListData(sortedResponse)
    }

    private fun initRecyclerView() {
        binding.apply {
            viewModel = this@BloodPressureFragment.viewModel
            llAdd.throttleClick {
                startActivity(
                    Intent(
                        activity, BpBloodPressureNewRecordActivity::class.java
                    )
                )
            }
            recyclerView.setItemViewCacheSize(6)
            val layoutManager = LinearLayoutManager(activity)
            layoutManager.orientation = LinearLayoutManager.VERTICAL
            recyclerView.layoutManager = layoutManager
            trackerBloodPressureAdapter.setOnAdapterClickListener(this@BloodPressureFragment)
            trackerBloodPressureAdapter.setActivity(activity, this@BloodPressureFragment.viewModel)
            trackerBloodPressureAdapter.setHeaderView(
                LayoutInflater.from(activity)
                    .inflate(R.layout.blood_pressure_header_layout_bg, recyclerView, false)
            )
            trackerBloodPressureAdapter.setHeaderFiveView(
                LayoutInflater.from(activity)
                    .inflate(R.layout.blood_pressure_header_sort_layout_bg, recyclerView, false)
            )
            trackerBloodPressureAdapter.setFooterView(
                LayoutInflater.from(activity)
                    .inflate(R.layout.blood_pressure_footer_layout_bg, recyclerView, false)
            )
            recyclerView.adapter = trackerBloodPressureAdapter
            val marginFirstTop = resources.getDimensionPixelSize(R.dimen.rate_list_margin_top)
            recyclerView.addItemDecoration(
                BPTrackSpacingItemDecoration(
                    bottomSpacing = if (type == Constants.BLOOD_PRESSURE_ACTIVITY) {
                        resources.getDimensionPixelSize(R.dimen.rate_list_margin_top)
                    } else {
                        resources.getDimensionPixelSize(R.dimen.activity_vertical_margin)
                    }, 0, marginFirstTop
                )
            )
        }
    }

    override fun onItemClick(id: String, date: Long) {
        val intent = Intent(
            activity, BloodPressureResultActivity::class.java
        )
        intent.putExtra("bpdId", id)
        intent.putExtra("date", date)
//        val type = if (type == Constants.BLOOD_PRESSURE_ACTIVITY) {
//            Constants.BLOOD_PRESSURE_ACTIVITY
//        } else {
//            Constants.BLOOD_PRESSURE_FRAGMENT
//        }
        intent.putExtra("type", Constants.BLOOD_PRESSURE_ACTIVITY)
        startActivity(intent)
    }

    override fun onHistoryClick() {
        //列表页
        startActivity(Intent(activity, BpBloodPressureHistoryListActivity::class.java))
    }

    /**
     * 文章详情
     */
    override fun articleItemClick(title: String, drawableId: Int) {
        if (type == Constants.BLOOD_PRESSURE_ACTIVITY) {
            (activity as BloodPressureViewActivity).startArticleActivity(
                title, drawableId, Constants.BLOOD_PRESSURE_ACTIVITY
            )
        } else {
            (activity as BpMainActivity).startArticleActivity(
                title, drawableId, Constants.BLOOD_PRESSURE_FRAGMENT
            )
        }
    }
}